package types

import (
	"database/sql/driver"
	"fmt"
	"strconv"
	"strings"

	"gitee.com/joseelin/goserve/x"
)

type IntArray []int

func (p IntArray) Value() (driver.Value, error) {
	v := ""
	if p != nil {
		arr := make([]string, len(p))
		for k, v := range p {
			arr[k] = fmt.Sprint(v)
		}
		v = strings.Join(arr, ",")
	}
	return driver.Value(v), nil
}
func (p *IntArray) Scan(src interface{}) error {
	var source string
	switch src.(type) {
	case string:
		source = src.(string)
	case []byte:
		source = string(src.([]byte))
	}
	if len(strings.Trim(source, " ")) == 0 {
		*p = make(IntArray, 0)
		return nil
	}
	arr := strings.Split(source, ",")
	*p = make(IntArray, len(arr))
	for i, v := range arr {
		(*p)[i], _ = strconv.Atoi(v)
	}
	return nil
}
func (p *IntArray) Contains(target int) bool {
	if x.Empty(p) {
		return false
	}
	for _, v := range *p {
		if v == target {
			return true
		}
	}
	return false
}
